package com.xin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xin.entity.crm.MenuEntity;
import com.xin.mapper.MenuMapper;
import com.xin.service.MenuService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> implements MenuService {

    /**
     * 返回员工拥有的菜单列表，并将转换成树结构
     * @param employeeId
     * @return
     */
    @Override
    public List<MenuEntity> queryListParentId(Long employeeId) {
        //查询员工拥有的菜单列表
        List<MenuEntity> employeeHasMenu = this.baseMapper.findEmployeeHasMenu(employeeId);
        //将菜单列表封装成树结构
        Map<Long, MenuEntity> menuMap = employeeHasMenu.stream().collect(Collectors.toMap(item -> item.getId(), item -> item));

        menuMap.forEach((key,value)->{
            Long parentId = value.getParentId();
            if (parentId!=null&&parentId.longValue()!=0){
                MenuEntity menuEntity = menuMap.get(parentId);
                if (menuEntity.getChild()==null) menuEntity.setChild(new ArrayList<MenuEntity>());
                menuEntity.getChild().add(value);
            }
        });
        //从菜单的父菜单开始返回
        List<MenuEntity> collect = menuMap.values().stream().filter(item -> item.getParentId() == null || item.getParentId().longValue() == 0).collect(Collectors.toList());

        return collect;
    }
}
